package com.iflysse.utils;

import com.alibaba.fastjson.JSONObject;
import com.iflysse.common.ResultEnum;
import com.iflysse.pojo.bo.CommonBoResp;
import com.iflysse.pojo.po.common.CommonPoResp;
import com.iflysse.pojo.vo.common.CommonVoResp;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;


public class CommonUtil {

    private static final String emailPrefix="尊敬的用户：\r\n您好！\r\n您在智能系统学" +
            "习平台使用了密码重置功能，请通过下面的地址" +
            "修改密码：\r\n";
    private static final String emailContent="http://139.196.38.160/reset-password?info=";
    public static final String emailSuffix="注意：该链接将于60分钟后失效\r\n感谢您的支持" +
            "并欢迎您再次使用本系统！\r\n此邮件为系统" +
            "自动发送，请勿直接回复！\r\n";

    public static final String pattern="yyyy-MM-dd HH:mm";


    /**
     * 拼接邮箱内容
     * @param param
     * @return
     */
    public static String bufferEmailInfo(String param){
        StringBuffer sb=new StringBuffer();
        sb.append(emailPrefix);
        sb.append(emailContent+param).append("\r\n");
        sb.append(emailSuffix);
        return sb.toString();
    }



    /**
     * 时间格式转换  string ——>目标类型的date
     * @param source
     * @param pattern
     * @return
     * @throws ParseException
     */
    public static Date stringSourceToDate(String source,String pattern) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat(pattern);
       Date target= sdf.parse(source);
       return target;
    }


    /**
     * 时间格式转换  date ——>目标类型的String
     * @param date
     * @param pattern
     * @return
     */
    public static String dateSourceToString(Date date,String pattern){
        SimpleDateFormat sdf=new SimpleDateFormat(pattern);
       String target= sdf.format(date);
       return target;
    }




    /**
     * 业务层增删改响应bean处理
     * @param commonBoResp
     * @param commonVoResp
     */
    public static void printBoResultToVoResult(CommonBoResp commonBoResp,CommonVoResp commonVoResp) {
        if(commonBoResp.getCode()==ResultEnum.SUCCESS.getCode()) {
            commonVoResp.setMsg(ResultEnum.SUCCESS.getMsg());
            commonVoResp.setCode(ResultEnum.SUCCESS.getCode());

        }else{
            commonVoResp.setMsg(commonBoResp.getMsg());
            commonVoResp.setCode(commonBoResp.getCode());

        }

    }



    /**
     * 业务层增删改响应bean处理
     * @param commonBoResp
     * @param i
     */
    public static void printToBoResult(CommonBoResp commonBoResp,int i) {
        if(i<1){
            commonBoResp.setCode(ResultEnum.NOTSUCCESS.getCode());
            commonBoResp.setMsg(ResultEnum.NOTSUCCESS.getMsg());
        }else{
            commonBoResp.setCode(ResultEnum.SUCCESS.getCode());
            commonBoResp.setMsg(ResultEnum.SUCCESS.getMsg());
        }

    }

    /**
     * 业务层增删改响应bean处理
     * @param commonPoResp
     * @param i
     */
    public static void printToPoResult(CommonPoResp commonPoResp, int i) {
        if(i<1){
            commonPoResp.setCode(ResultEnum.NOTSUCCESS.getCode());
            commonPoResp.setMsg(ResultEnum.NOTSUCCESS.getMsg());
        }else{
            commonPoResp.setCode(ResultEnum.SUCCESS.getCode());
            commonPoResp.setMsg(ResultEnum.SUCCESS.getMsg());
        }

    }



    /**
     * servlet像前端输出异常bean
     * @param response
     * @param commonVoResp
     */
    public static void printError(CommonVoResp commonVoResp){
        commonVoResp.setCode(ResultEnum.ERROR.getCode());
        commonVoResp.setMsg(ResultEnum.ERROR.getMsg());
//        CommonUtil.printJson(response,commonVoResp);
    }

    /**
     * 多媒体文件上传的类型有误，向前端输出响应信息
     * @param response
     * @param commonVoResp
     * @throws IOException
     */
    public static void prinrFileError(HttpServletResponse response , CommonVoResp commonVoResp)throws IOException {
        commonVoResp.setCode(ResultEnum.TYPEFILEERROR.getCode());
        commonVoResp.setMsg(ResultEnum.TYPEFILEERROR.getMsg());
//        CommonUtil.printJson(response,commonVoResp);
    }




    /**
     * servlet像前端输出响应bean
     * @param response
     * @param commonVoResp
     */
    public static synchronized void printJson(HttpServletResponse response , CommonVoResp commonVoResp)throws IOException {
       PrintWriter out=  response.getWriter();
       String json= JSONObject.toJSONString(commonVoResp);
       out.print(json);
       out.flush();
       out.close();
    }


    /**
     * 拼接base64码输出到前端
     * @param base
     * @param type
     * @throws IOException
     */
    public static String appendBaseToWebApp(String base,String type)throws IOException {
        String prefix="data:image/";
        String suffix=";base64,";
        String result=prefix+type+suffix+base;
        return result;
    }


    /**
     * 类型转换工具   VO转BO ，BO转PO  相同属性可转 ，不同属性手动set
     * @param source
     * @param targetClazz
     * @param <T>
     * @return
     */
    public static <T>T objToObj(Object source, Class<T> targetClazz) {
        try {
            T target = targetClazz.newInstance();
            Class sourceClazz = source.getClass();

            Field[] sourceFields = sourceClazz.getDeclaredFields();
            Field[] targetFields = target.getClass().getDeclaredFields();

            for (Field sourceField : sourceFields) {
                sourceField.setAccessible(true);
                for (Field targetField : targetFields) {
                    if (targetField.getName().equals(sourceField.getName()) && targetField.getType() == sourceField.getType()) {
                        int mod = targetField.getModifiers();
                        if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                            continue;
                        }
                        targetField.setAccessible(true);
                        targetField.set(target, sourceField.get(source));
                        break;
                    }
                }
            }
            return target;
        }catch (Exception e){
            return null;
        }
    }


    /**
     * 邮件发送方法
     * @param to  收件人邮箱
     * @param emailMsg   邮件内容
     * @return
     */
    public static boolean sendMail(String to, String emailMsg) {

        try {
            Context context = new InitialContext();
            String emailUser ="862293777@qq.com"; //(String) context.lookup("java:comp/env/emailUser");
            String emailPwd ="exebjubkzgwxbbai";// (String) context.lookup("java:comp/env/emailPwd");
            String emailHost ="smtp.qq.com";// (String) context.lookup("java:comp/env/emailHost");
            String emailAuth ="true"; //(String) context.lookup("java:comp/env/emailAuth");
            String emailProtocol ="smtp"; //(String) context.lookup("java:comp/env/emailProtocol");
            int emailPort =465; //(Integer) context.lookup("java:comp/env/emailPort");

            // 获取系统环境信息
            Properties props = System.getProperties();
            // 设置邮件服务器
            props.setProperty("mail.smtp.host", emailHost);
            // 设置密码认证
            props.setProperty("mail.smtp.auth", emailAuth);
            // 设置传输协议
            props.setProperty("mail.transport.protocol", emailProtocol);

            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            // 创建session对象
            Session session = Session.getInstance(props);
            // 设置输出日志
            session.setDebug(true);

            // 邮件发送对象
            MimeMessage message = new MimeMessage(session);
            // 设置发件人
            message.setFrom(new InternetAddress(emailUser));
            // 设置邮件主题
            message.setSubject("重置密码邮件");
            // 设置邮件内容
             message.setText(emailMsg);
            // 如果带网页内容使用Content发送
//            message.setContent((emailMsg), "text/html;charset=utf-8");

            // 获取邮件发送管道
            Transport transport = session.getTransport();
            // 连接管道
            transport.connect(emailHost, emailPort, emailUser, emailPwd);
            // 发送邮件
            transport.sendMessage(message, new Address[] { new InternetAddress(to) });
            // 关闭管道
            transport.close();
            return true;
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

}
